<template>
  <div id="geoMap"></div>
</template>
<script setup>
import { onMounted } from "vue";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile.js";
import XYZ from "ol/source/XYZ.js";
import ZoomToExtent from "ol/control/ZoomToExtent.js";
import ZoomSlider from "ol/control/ZoomSlider.js";
import FullScreen from "ol/control/FullScreen.js";
import Style from "ol/style/Style.js";
import CircleStyle from "ol/style/Circle.js";
import Fill from "ol/style/Fill.js";
import Stroke from "ol/style/Stroke.js";
import VectorSource from "ol/source/Vector.js";
import VectorLayer from "ol/layer/Vector";
import GeoJSON from "ol/format/GeoJSON.js";
let map = undefined;

// 初始化一个高德地图
const gaode = new TileLayer({
  title: "高德地图",
  source: new XYZ({
    url: "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    wrapX: false,
  }),
});
// 视图跳转控件
const zoomToExtent = new ZoomToExtent({
  extent: [
    113.20956348921601, 21.863189834881656, 113.305570130008,
    21.983070782352733,
  ],
});
// 放大缩小控件
const zoomslider = new ZoomSlider();
// 全屏控件
const fullScreen = new FullScreen();

// 1. 创建geojson数据
const data = {
  type: "FeatureCollection",
  features: [
    {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [113.25589282043693, 21.89897070201314],
      },
    },
  ],
};
// 2. 将数据添加到矢量图中
let source = new VectorSource({
  features: new GeoJSON().readFeatures(data),
});

// 3. 将矢量图设置为图层
let layer = new VectorLayer({ source });
// 4. 设置样式
let style = new Style({
  image: new CircleStyle({
    // radius设置点的半径 单位degree
    radius: 10,
    // 设置填充颜色
    fill: new Fill({
      color: "#ff2d51",
    }),
    // 设置边框粗细及颜色
    stroke: new Stroke({
      width: 2,
      color: "#333",
    }),
  }),
});

layer.setStyle(style);

onMounted(() => {
  map = new Map({
    target: "geoMap",
    layers: [gaode, layer],
    view: new View({
      center: [113.25589282043693, 21.89897070201314],
      // 设置地图放大级别
      zoom: 14,
      projection: "EPSG:4326",
    }),
  });
  map.addControl(zoomToExtent);
  map.addControl(zoomslider);
  map.addControl(fullScreen);
  map.on("moveend", (e) => {
    console.log("🚀 ~ onMounted ~ e:", e);
  });
  map.on("rendercomplete", () => {
    console.log("渲染完成");
  });
  map.on("click", (e) => {
    console.log("地图点击", e);
  });
});
</script>
<style scoped lang=scss>
#geoMap {
  width: 100%;
  height: 100%;
  /deep/ .ol-zoomslider {
    top: 7em;
  }
}
</style>